package com.cmdi.gateway.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @Description: java类作用描述
 * @Author: gaozb
 * @Date: 2021/9/7$ 16:44$
 * @Version: 1.0
 */
@Service
public class GatewayDynamicRouteService implements ApplicationEventPublisherAware {
    @Autowired
    private CustomRedisRouteDefinitionRepository customRedisRouteDefinitionRepository;
    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    public void notifyChanged() {
        this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
    }

    public int add(RouteDefinition route) {
        customRedisRouteDefinitionRepository.save(Mono.just(route)).subscribe();
        applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
        return 1;
    }

    public int update(RouteDefinition route) {
        customRedisRouteDefinitionRepository.delete(Mono.just(route.getId()));
        customRedisRouteDefinitionRepository.save(Mono.just(route)).subscribe();
        applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
        return 1;
    }


    public Mono<Void> delete(String id) {
        return customRedisRouteDefinitionRepository.delete(Mono.just(id));
    }

    public Flux<RouteDefinition> get() {
        return customRedisRouteDefinitionRepository.getRouteDefinitions();
    }

}